(function(window,undefined){
	/*개발자 이름, 파일명*/
	var Jpark = {};	
	
	/*page 작성*/
	var couponManage = Jpark.couponManagement = {};
	var qnaWrite = Jpark.qnaWrite = {};
	//var testPage2 = Sample.testPage2 = {};
	//var testPage3 = Sample.testPage3 = {};
	
	window.Jpark = window.Jpark || Jpark;
	
	
	var loadSalerCouponList = function(succssCallback){
		if(!succssCallback){
			alert(NONE_CALLBACK);
		}
		
		$.ajax({
			type:'post',
			url:ajaxURL+"coupon.php?action=loadSalerCouponList",
			data:{user_id:sessionStorage.getItem("user_id")},
			dataType:'json',
			success:function(result){
				console.log(result);
				couponManage.data = result;
				succssCallback(result);
			}
		});
	};
	
	var loadSalerCouponStatue = function(succssCallback){
		if(!succssCallback){
			alert(NONE_CALLBACK);
		}
		
		$.ajax({
			type:'post',
			url:ajaxURL+"coupon.php?action=loadSalerCouponStatue",
			data:{user_id:sessionStorage.getItem("user_id")},
			dataType:'json',
			success:function(result){
				console.log(result);
				
				succssCallback(result);
			}
		});
	};
	
	var addSalerCoupon = function(statue){
		var c = couponManage.createCoupon;
		alert("11");
		$.ajax({
			type:'post',
			url:ajaxURL+"coupon.php?action=addSalerCoupon",
			data:{
				  user_id : sessionStorage.getItem("user_id"),
				  count : c.count,
				  day : c.day,
				  discription : c.dis,
				  dc_reward : c.dc_reward,
				  image : c.image,
				  title : c.title,
				  year : c.year,
				  month : c.month,
				  statue : statue				
				},
			dataType:'json',
			success:function(result){
				console.log(result);
				if(result == "success"){ location.href="seller_coupon.php"; } 
				else{alert("오류");}
				//succssCallback(result);
			},
			error:function(err){
				console.log(err);
			}
			
		});
	};
	
	var delSalerCoupon = function(_coupon_id){
	
		
		$.ajax({
			type:'post',
			url:ajaxURL+"coupon.php?action=delSalerCoupon",
			data:{coupon_id:_coupon_id},
			dataType:'json',
			success:function(result){
				console.log(result);
				if(result == "success"){ location.href="seller_coupon.php"; } 
				else{alert("오류");}
				//succssCallback(result);
			},
			error:function(e){
				console.log(e);
			}
		});
	};
	
	couponManage.salerCouponListBlock = function(){
		loadSalerCouponList(function(result){/*delFuctionNmae ajax 연동*/
			console.log("qq");
			console.log(result);
			$('ul.couponList').empty();
			for(i = 0 ; i<result.length ; i++){
				template.salerCouponList(result[i]);
			}
			
			
			
			salerCouponListListener();
			
							
			console.log(result);
		});
	};
	
	couponManage.salerCouponStatueBlock = function(){
		loadSalerCouponStatue(function(result){
			
			//$('div.infoWidget').empty();
			template.salerCouponStatue(result);
			
							
			console.log(result);
		});
	};
	
	qnaWrite.qnaWriteBlock = function(){
		qnaWriteListener();
		
	};
	
	
	
	qnaWriteListener = function(){
		var qnaObj = {};
		var _base = "#qnaWrite ";
		$(_base + " .buttonWrap img").off("click").on("click",function(event){
			event.preventDefault();
			qnaObj.name = $(_base + " #company").val();
			qnaObj.mail = $(_base + " #mail").val() + "@" + $(_base + " #mailAddress").val();
			qnaObj.phone = $(_base + " #phone1").val() + $(_base + " #phone2").val() + $(_base + " #phone3").val();
			qnaObj.type = $(_base + " #type").val();
			qnaObj.title = $(_base + " #name").val();
			qnaObj.msg = $(_base + " textarea.textInput").val();
			
			var isCommit = checkQnaWrite(qnaObj);
			if(isCommit == true) sendQnaWrite(qnaObj);
			else alert("필수 항복을 입력하세요");
			
		});
		
		
		
		$(_base + " #selectMail").change(function(){
			event.preventDefault();
			if($(this).val() == "self"){
				$(_base + " #mailAddress").removeAttr("disabled");	
				
				
			} 
			else {
				var _temp = $(_base + " #selectMail").val();
				$(_base + " #mailAddress").attr("disabled","disabled");
				$(_base + " #mailAddress").attr("value",_temp);
				
			}
		});
		
		$(_base + " #company").keydown(a = function(){
			//event.preventDefault();
			if($(this).val().length >= 1) $("#company").parent().parent().find("td:nth(1)").text("완료");
			else $("#company").parent().parent().find("td:nth(1)").text("이름을 입력해주세요.");			
		}).keyup(a);
		
		$(_base + " #mail").keydown(a=function(){
			//event.preventDefault();
			if($(_base + " #mail").val().length >= 1 && $(_base+" #mailAddress").val().length >=3 && $(_base+" #mailAddress").val().split(".")[0].length >=1 && $(_base+" #mailAddress").val().split(".")[1].length >=1) $(this).parent().parent().find("td:nth(1)").text("완료");
			else $(this).parent().parent().find("td:nth(1)").text("이메일을 입력해주세요.");			
		}).keyup(a);
		$(_base + " #mailAddress").keydown(a=function(){
			//event.preventDefault();
			if($(_base + " #mail").val().length >= 1 && $(_base+" #mailAddress").val().length >=5 && $(_base+" #mailAddress").val().split(".")[0].length >=1 && $(_base+" #mailAddress").val().split(".")[1].length >=1) $(this).parent().parent().find("td:nth(1)").text("완료");
			else $(this).parent().parent().find("td:nth(1)").text("이메일을 입력해주세요.");			
		}).keyup(a);
		$(_base + " #selectMail").change(function(){
			//event.preventDefault();
			if($(_base + " #mail").val().length >= 1 && $(_base+" #mailAddress").val().length >=3 && $(_base+" #mailAddress").val().split(".")[0].length >=1 && $(_base+" #mailAddress").val().split(".")[1].length >=1) $(this).parent().parent().find("td:nth(1)").text("완료");
			else $(this).parent().parent().find("td:nth(1)").text("이메일을 입력해주세요.");			
		});
		
		$(_base + " #phone2").keydown(a=function(){
			//event.preventDefault();
			if($(this).val().length >= 3 && $(_base+" #phone3").val().length >= 4) $(this).parent().parent().find("td:nth(1)").text("완료");
			else $(this).parent().parent().find("td:nth(1)").text("휴대폰 번호를 입력해주세요.");			
		}).keyup(a);
		$(_base + " #phone3").keydown(a=function(){
			//event.preventDefault();
			if($(this).val().length >= 4 && $(_base+" #phone2").val().length >= 3) $(this).parent().parent().find("td:nth(1)").text("완료");
			else $(this).parent().parent().find("td:nth(1)").text("휴대폰 번호를 입력해주세요.");			
		}).keyup(a);
		
		$(_base + " #name").keydown(a=function(){
			//event.preventDefault();
			if($(this).val().length >= 1) $(this).parent().parent().find("td:nth(1)").text("완료");
			else $(this).parent().parent().find("td:nth(1)").text("제목을 입력하세요.");			
		}).keyup(a);
		
		$(_base + " table textarea").keydown(a=function(){
			//event.preventDefault();
			if($(this).val().length >= 1) $(this).parent().parent().find("td:nth(1)").text("완료");
			else $(this).parent().parent().find("td:nth(1)").text("문의의 상세 내용을 입력해주세요.");			
		}).keyup(a);
		$(_base + " #type").change(a=function(){
			//event.preventDefault();
			if($(this).val().length >= 1) $(this).parent().parent().find("td:nth(1)").text("완료");
			else $(this).parent().parent().find("td:nth(1)").text("문의유형을 선택해 주세요.");			
		}).keyup(a);
	}
	checkQnaWrite = function(qna){
		console.log(qna);
		var isCheck = true;
		if(qna.name.length < 1) isCheck =false;
	//	console.log(qna.mail.split("@")[1].split(".")[1]);
		if(qna.mail.split("@")[1].split(".")[1] ==null || qna.mail.split("@")[1].split(".")[1] =="" ) isCheck = false;
		if(qna.mail.split("@")[0] == null || qna.mail.split("@")[0] == "" ) isCheck = false;
		if(qna.phone.length < 10 || qna.phone.length == 0)isCheck = false;
		if(qna.title.length <= 0) isCheck = false;
		if(qna.msg.length <= 0) isCheck = false;
		
		return isCheck;
		
		
	}
	
	sendQnaWrite = function(qna){
		
		console.log(qna);
		$.ajax({
			type:'post',
			url:ajaxURL+"account.php?action=sendQnaMail",
			data:{mail : qna.mail,
				  msg : qna.msg,
				  name : qna.name,
				  phone : qna.phone,
				  title : qna.title,
				  type : qna.type
				  
				},
			dataType:'json',
			success:function(result){
				console.log(result);
				
				if(result == "success")alert("문의 신청이 되었습니다.");
				else alert("메일을 전송하는데 실패하였습니다.");
			},
			error : function(e){
				console.log(e);
			}
		});
		
	}
	
	salerCouponListListener = function(){
		$('.del_coupon_bt').off('click').on("click",function(event){
			event.preventDefault();
			var _coupon_id = $(this).attr("coupon_id");
			
			template.delCouponModal(couponManage.data,_coupon_id);
		});
	}


	delCouponModalListener=function(coupon_id){
		
		$('.del_coupon_ok_bt').off('click').on("click",function(event){
			event.preventDefault();
			
			delSalerCoupon(coupon_id);
			
		});
		$('#modal_warp #modal_cancel_bt').off('click').on("click",function(event){
			event.preventDefault();
			$("#modal_warp").empty();
		});
	}
	
	createCouponModalListener = function(){
    	$('#discount_coupon_bt').off('click').on("click",function(event){
			event.preventDefault();
			$("#discount_coupon_bt , #plus_coupon_bt").parent().removeClass("active");
			$("#discount_coupon_bt").parent().addClass("active");
			$("#discountCoupon").show();	
			$("#plusCoupon").hide();
		});
    	$('#plus_coupon_bt').off('click').on("click",function(event){
			event.preventDefault();
			$("#discount_coupon_bt , #plus_coupon_bt").parent().removeClass("active");
			$("#plus_coupon_bt").parent().addClass("active");
			$("#discountCoupon").hide();	
			$("#plusCoupon").show();
		});	 
		$('#modal_warp #modal_cancel_bt').off('click').on("click",function(event){
			event.preventDefault();
			$("#modal_warp").empty();
		});
		
		$('#create_discount_coupon_bt , #create_plus_coupon_bt').off('click').on("click",function(event){
			event.preventDefault();
			var c = {};
			couponManage.createCoupon = c;
			
			c.image =  $("input.input_dis_image").val();
			c.title =  $("input.input_dis_title").val();
			c.dc_reward = $("input.input_dis_disrate").val();
			c.dis =  $("textarea.input_dis_dis").val();
			c.count =  $("input.input_dis_count").val();
			c.year = $(".input_dis_year").val();
			c.month = $(".input_dis_month").val();
			c.day = $(".input_dis_day").val();
			console.log(couponManage.createCoupon);
			addSalerCoupon("discount");
		});
		$(".input_dis_year , .input_dis_month").change(function(){
			
			var year = $(".input_dis_year").val();
			var month = $(".input_dis_month").val();
			var target = ".input_dis_day";
			makeDay(year,month,target);
		})
		
		
		$('#create_plus_coupon_bt').off('click').on("click",function(event){
			event.preventDefault();
			var c = {};
			couponManage.createCoupon = c;
			
			c.image =  $("input.input_plus_image").val();
			c.title =  $("input.input_plus_title").val();
			c.dc_reward = $("input.input_plus_item").val();
			c.dis =  $("textarea.input_plus_dis").val();
			c.count =  $("input.input_plus_count").val();
			c.year = $(".input_plus_year").val();
			c.month = $(".input_plus_month").val();
			c.day = $(".input_plus_day").val();
			console.log(couponManage.createCoupon);
			addSalerCoupon("plus");
		});
		$(".input_plus_year , .input_plus_month").change(function(){
			
			var year = $(".input_plus_year").val();
			var month = $(".input_plus_month").val();
			var target = ".input_plus_day";
			makeDay(year,month,target);
		})
		
		
		
		
		//couponManage.createCoupon
		
	}
	
	var template = {
		salerCouponStatue : function(result){
			info = '';
			info += '<table class="dataTable">';
	        info += '<tr>';
	        info += '<th>진행중인 쿠폰</th>';
	        info += '<td><b>'+result.cur_count+'</b>개</td>';
	        info += '</tr>';
	        info += '<tr>';
	        info += '<th>총 쿠폰 발급</th>';
	        info += '<td><b>'+result.all_count+'</b>회</td>';
	        info += '</tr>';
	        info += '<tr>';
	        info += '<th>쿠폰 회수율</th>';
	        info += '<td><b>'+result.rate+'</b>%</td>';
	        info += '</tr>';
	        info += '</table>';
	        info += '<a href="#" class="create_coupon_bt"><img src="images/btn_seller_coupon_add.png" alt="신규 쿠폰 발급" /></a>';
	      
        	$("div.infoWidget").html(info);
        	
        	$('.create_coupon_bt').off('click').on("click",function(event){
				event.preventDefault();
					
				template.createCouponModal();
			});
        		
		},
		createCouponModal : function(){
			var info ='';
		 	info += '<div class="modalBg"></div>';
    		info += '<div id="couponMake" class="modal box">';
    		info += '<h3 class="left"><img src="images/titles/coupon_make.png" alt="신규 쿠폰 발급"/></h3>';
    		info += '<a href="#" class="modalClose right" id="modal_cancel_bt">닫기</a>';
    		info += '<div class="clear"></div>';
    		info += '<ul id="tab_1" class="tabHead">';
    		info += '<li class="active"><a href="#discountCoupon" id="discount_coupon_bt">할인쿠폰</a></li>';
    		info += '<li><a href="#plusCoupon" id="plus_coupon_bt">플러스쿠폰</a></li>';
    		info += '<div class="clear"></div>';
    		info += '</ul>';
    		info += '<div id="discountCoupon" class="writeTextWrap">';
    		info += '<h4>쿠폰정보</h4>';
    		info += '<table>';
    		info += '<tr>';
    		info += '<th style="width:100px;">';
    		info += '쿠폰이미지';
    		info += '</th>';
    		info += '<td>';
    		info += '<input class="textInput input_dis_image" style="width:200px;"/> <img src="images/btn_add_photo.png" alt="btn_add_photo" />';
    		info += '</td>';
    		info += '</tr>';
    		info += '<tr>';
    		info += '<th style="width:100px;">';
    		info += '쿠폰제목';
    		info += '</th>';
    		info += '<td>';
    		info += '<input class="textInput input_dis_title" style="width:300px;"/>';
    		info += '</td></tr><tr><th>할인율</th><td>';
    		info += '<input class="textInput input_dis_disrate" style="width:100px;"/> %';
    		info += '</td></tr><tr><th>쿠폰내용</th><td>';
    		info += '<textarea  class="textInput input_dis_dis" style="width:440px; height:40px"></textarea>';
    		info += '</td></tr></table><h4>발행정보</h4>';
    		info += '<table><tr><th style="width:100px;">발행기간</th><td>';
    		info += '<select class="input_dis_year">';
    		info += '<option value="2013">2013년</option><option value="2014">2014년</option><option value="2015">2015년</option>';
    		info += '<option value="2016">2016년</option><option value="2017">2017년</option><option value="2018">2018년</option>';
    		info += '</select>';
    		info += '<select class="input_dis_month">';
    		info += '<option value="1">1월</option><option value="2">2월</option><option value="3">3월</option>';
    		info += '<option value="4">4월</option><option value="5">5월</option><option value="6">6월</option>';
    		info += '<option value="7">7월</option><option value="8">8월</option><option value="9">9월</option>';
    		info += '<option value="10">10월</option><option value="11">11월</option><option value="12">12월</option>';
    		info += '</select>';
    		info += '<select class="input_dis_day"></select>';
    		info += '</td></tr><tr><th style="width:100px;">발급매수</th><td>';
    		info += '<input class="textInput input_dis_count" style="width:100px;"/>';
    		info += '</td></tr></table><div class="buttonWrap">';
    		info += '<a href="#" id="create_discount_coupon_bt"><img src="images/btn_add_coupon.png" alt="btn_add_coupon" /></a> <a href="#" id="modal_cancel_bt"><img src="images/btn_cancel.png" alt="btn_add_coupon" /></a>';
    		info += '</div></div><div id="plusCoupon" class="writeTextWrap"><h4>쿠폰정보</h4>';
    		info += '<table><tr><th style="width:100px;">쿠폰이미지</th><td>';
    		info += '<input class="textInput input_plus_image" style="width:200px;"/> <img src="images/btn_add_photo.png" alt="btn_add_photo" />';
    		info += '</td></tr><tr><th style="width:100px;">쿠폰제목</th><td>';
    		info += '<input class="textInput input_plus_title" style="width:300px;"/>';
    		info += '</td></tr><tr><th>사은품</th><td>';
    		info += '<input class="textInput input_plus_item" style="width:300px;"/> ';
    		info += '</td></tr><tr><th>쿠폰내용</th><td>';
    		info += '<textarea  class="textInput input_plus_dis" style="width:440px; height:40px"></textarea>';
    		info += '</td></tr></table><h4>발행정보</h4><table><tr><th style="width:100px;">발행기간</th><td>';
    		info += '<select class="input_plus_year">';
    		info += '<option value="2013">2013년</option><option value="2014">2014년</option><option value="2015">2015년</option>';
    		info += '<option value="2016">2016년</option><option value="2017">2017년</option><option value="2018">2018년</option>';
    		info += '</select>';
    		info += '<select class="input_plus_month">';
    		info += '<option value="1">1월</option><option value="2">2월</option><option value="3">3월</option>';
    		info += '<option value="4">4월</option><option value="5">5월</option><option value="6">6월</option>';
    		info += '<option value="7">7월</option><option value="8">8월</option><option value="9">9월</option>';
    		info += '<option value="10">10월</option><option value="11">11월</option><option value="12">12월</option>';    		    		
    		info += '</select>';
    		info += '<select class="input_plus_day">';
    		
    		
    		info += '</select>';
    		info += '</td></tr><tr><th style="width:100px;">발급매수</th><td>';
    		info += '<input class="textInput input_plus_count" style="width:100px;"/>';
    		info += '</td></tr></table><div class="buttonWrap">';
    		info += '<a href="#" id="create_plus_coupon_bt"><img src="images/btn_add_coupon.png" alt="btn_add_coupon" /></a> <a href="#" id="modal_cancel_bt"><img src="images/btn_cancel.png" alt="btn_add_coupon" /></a>';
    		info += '</div></div></div>';
    			
    		$("#modal_warp").html(info);	
    		$("#discountCoupon").show();	
			$("#plusCoupon").hide();
    		
    		createCouponModalListener();
    		 
    		
			
		},
		salerCouponList : function(result){
			console.log("list");
			console.log(result);
			
			
			var _yearMonthDay = result.expired_date.split(" ")[0];
			var _year = _yearMonthDay.split("-")[0];
			var _month = _yearMonthDay.split("-")[1];
			var _day = _yearMonthDay.split("-")[2];
			
			
			
			var info = '';		
			
			info += '<li class="active">';
			info += '<div class="thumbWrap">';
			info += '<a href="seller_store.php">';
			info += '<img src="'+result.image+'" alt="thumb_store_1" width ="160px" height="120px">';
			info += '</a>';
			info += '</div>';
			info += '<div class="infoWrap">';
			info += '<h4 class="title"></h4>';
			info += '<div class="store"><a href="store_view.php?id='+result.store_id+'">'+result.title+'</a></div>';
			info += '<div class="tags">'+result.category_name+' <span>|</span> '+result.addr+'</div>';
			info += '<div class="values">';
			info += '단골 <b>'+result.favorite_count+'</b>명';
			info += '</div>';
			info += '<div class="date">'+_month+ '월' +_day+ '일 까지</div>';
			info += '</div>	';
			info += '<div class="sharedownWrap delete">';
			info += '<a href="#" class="del_coupon_bt" coupon_id="'+result.coupon_id+'">삭제하기</a>';
			info += '<div class="cnt"><span><b>'+result.count+'</b>장 남음</span></div>';
			info += '</div>';
			info += '<div class="clear"></div>';
			info += '</li>'; 
	
			$('ul.couponList').append(info);
			
		},
		
		delCouponModal : function(data,coupon_id){
			
			var _data;
			for(i = 0 ; i < data.length ; i++){
				if(data[i].coupon_id == coupon_id) {_data = data[i]; break;} 	
			}
			
			
			
			var info = '';
			info += '<div class="modalBg"></div>';
		    
		    info += '<div id="modalMsg" class="modal box">';
		    info += '<h3 class="left text">쿠폰 삭제</h3>';
		    info += '<a href="#" class="modalClose right" id="modal_cancel_bt">닫기</a>';
		    info += '<div class="clear"></div>';
			info += '<div class="message">';
		    info += '유효기간이 <b>'+_data.expired_day+'</b>일 남은</br> <b>'+_data.count+'</b>개의 쿠폰이 남았습니다.<br/>';
		    info += '삭제하시겠습니까?';
		    info += '</div>';
		    info += '<div class="buttonWrap">';
		    info +=	'<a href="#" class = "del_coupon_ok_bt" ><img src="images/btn_delete.png" alt="btn_add_coupon" /></a> <a href="#" id="modal_cancel_bt"><img src="images/btn_cancel.png" alt="btn_add_coupon" /></a>'; 
		    info += '</div>';    
		    info += '</div>';
		    $("#modal_warp").html(info);
		    delCouponModalListener(coupon_id);
		    
		}
	}
	
	function makeDay(year,month,target) { 
		var YEAR=year; 	
		var MONTH=month; 	
		var daysInMonth=new Date(new Date(YEAR,MONTH,1)-86400000).getDate(); 	
		var day = '';
		for(i = 1 ; i<daysInMonth+1 ; i++){
			day += '<option value="'+i+'">'+i+'일</option>';
		}
		$(target).html(day);
		return  
	} 
	
	
})(window);
